package com.jyy.prefabricated.service.impl;

import com.jyy.prefabricated.dto.CourseStudyTimeTecordDto;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.mapper.*;
import com.jyy.prefabricated.service.CourseCategoryService;
import com.jyy.prefabricated.service.CoursePackageService;
import com.jyy.prefabricated.service.CourseStudyTimeTecordService;
import com.jyy.prefabricated.service.TrainingOrganizationStockService;
import com.jyy.prefabricated.utils.DateUtils;
import com.jyy.prefabricated.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学生随堂考管理表(StudentQuiz)表服务实现类
 *
 * @author makejava
 * @since 2021-10-11 13:49:01
 */
@Service("CourseStudyTimeTecordService")
public class CourseStudyTimeTecordServiceImpl implements CourseStudyTimeTecordService {
    @Resource
    private StudentQuizMapper studentQuizMapper;

    @Resource
    private CourseCategoryService courseCategoryService;

    @Resource
    private CoursePackageService coursePackageService;

    @Resource
    private CoursePackageMapper coursePackageMapper;

    @Resource
    private QuizRecordMapper quizRecordMapper;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private StudentQuizQuestionMapper studentQuizQuestionMapper;

    @Resource
    private ViewLogMapper viewLogMapper;

    @Resource
    private OrderInfoMapper orderInfoMapper;

    @Resource
    private TrainingOrganizationStockService trainingOrganizationStockService;

    @Resource
    private StudentCoursePackageMapper studentCoursePackageMapper;

    @Resource
    private StudentMapper studentMapper;


    /**
     * @param dto 主键
     * @return 是否成功
     */
    @Override
    public List<CourseStudyTimeTecordVo> selectCourseStudyTimeTecord(CourseStudyTimeTecordDto dto) {

        List<CourseStudyTimeTecordVo> result = new ArrayList<>();
        //获取所有课程包二级分类id集合
        List<CourseCategoryData> courseCategoryDataList = courseCategoryService.selectTree(0);

        for (CourseCategoryData courseCategoryData : courseCategoryDataList) {
            if (courseCategoryData.getChildren() != null && courseCategoryData.getChildren().size() > 0) {
                for (CourseCategoryData item : courseCategoryData.getChildren()) {
                    CourseStudyTimeTecordVo courseStudyTimeTecordVo = new CourseStudyTimeTecordVo();
                    //该专项二级分类id
                    courseStudyTimeTecordVo.setCategoryId(item.getId());
                    //该专项二级分类名称
                    courseStudyTimeTecordVo.setCategoryName(item.getCategory());
                    //二级分类下包含的课程包总数
                    List<Integer> categoryIds = coursePackageService.selectDeepCategoryIds(item.getId());
                    List<CoursePackage> coursePackageList = coursePackageService.selectDeepByParams(null, null, null, categoryIds, null, null, null, null);

                    if (coursePackageList != null && coursePackageList.size() > 0) {
                        //该专项下包含课程包总数量
                        courseStudyTimeTecordVo.setTotalCount(coursePackageList.size());

                        courseStudyTimeTecordVo.setCoursePackageList(coursePackageList);
                    }
                    result.add(courseStudyTimeTecordVo);
                }
            }
        }

        for (CourseStudyTimeTecordVo courseStudyTimeTecordVo : result) {

            List<Integer> ids = courseStudyTimeTecordVo.getCoursePackageList().stream().map(e -> e.getId()).collect(Collectors.toList());
            if (ids != null && ids.size() > 0) {
                List<TrainingOrganizationStock> trainingOrganizationStockList = trainingOrganizationStockService.selectByParams(null, null, dto.getTrainingOrganizationId(), null);
                int count = 0;
                //该专项学员学习人数
                int studyNum = 0;
                if (trainingOrganizationStockList != null && trainingOrganizationStockList.size() > 0) {
                    for (TrainingOrganizationStock item : trainingOrganizationStockList) {
                        if (ids.contains(item.getProductId()) && item.getWhetherOverdue() == true) {
                            count++;
                            List<StudentCoursePackage> list = studentCoursePackageMapper.selectByOrderId(item.getOrderId());
                            studyNum += list.size();
                        }
                    }
                }
                //该专项下已经购买课程包数量
                courseStudyTimeTecordVo.setPurchaseCount(count);
                courseStudyTimeTecordVo.setStudyNum(studyNum);
            }

        }

        return result;
    }

    //判断商品（课程包）是否过期
    public Boolean whetherOverdue(Integer orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
        if (orderInfo != null && orderInfo.getPayTime() != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date currdate = format.parse(orderInfo.getPayTime());
                Calendar ca = Calendar.getInstance();
                ca.setTime(currdate);
                if (orderInfo.getBuyType() != null && orderInfo.getBuyTypeNum() != null) {
                    if (orderInfo.getBuyType() == 0) {
                        ca.add(Calendar.YEAR, orderInfo.getBuyTypeNum());
                    } else if (orderInfo.getBuyType() == 1) {
                        ca.add(Calendar.MONTH, orderInfo.getBuyTypeNum());
                    } else if (orderInfo.getBuyType() == 2) {
                        ca.add(Calendar.WEEK_OF_YEAR, orderInfo.getBuyTypeNum());
                    } else if (orderInfo.getBuyType() == 3) {
                        ca.add(Calendar.DATE, orderInfo.getBuyTypeNum());
                    }
                }
                currdate = ca.getTime();
                long now = DateUtils.getUct8NowDate().getTime();
                if (currdate.getTime() < now) {
                    return false;
                }
            } catch (ParseException e) {
            }

        }
        return true;
    }

    @Override
    public List<CoursePackageTecordVo> selectByCategoryIdAndTrainingOrganizationId(Integer trainingOrganizationId, Integer categoryId) throws IOException, NoSuchAlgorithmException {

        List<CoursePackageTecordVo> result = new ArrayList<>();
        List<Integer> categoryIds = coursePackageService.selectDeepCategoryIds(categoryId);
        List<CoursePackage> coursePackageList = coursePackageService.selectDeepByParams(null, null, null, categoryIds, null, null, null, null);
        if (coursePackageList != null) {
            //该二级分类下，企业已经购买的课程包集合(未过期)
            List<Integer> ids = coursePackageList.stream().map(e -> e.getId()).collect(Collectors.toList());
            if (ids != null && ids.size() > 0) {

                List<TrainingOrganizationStock> trainingOrganizationStockList = trainingOrganizationStockService.selectByParams(null, null, trainingOrganizationId, null);
                if (trainingOrganizationStockList != null && trainingOrganizationStockList.size() > 0) {
                    for (TrainingOrganizationStock item : trainingOrganizationStockList) {
                        if (ids.contains(item.getProductId()) && item.getWhetherOverdue() == true) {
                            CoursePackage coursePackage = coursePackageMapper.selectByPrimaryKey(item.getProductId());
                            //没有包含随堂考的课程包不显示
                            if (coursePackage.getAreas() != null && coursePackage.getAreas().size() > 0) {
                                CoursePackageTecordVo coursePackageTecordVo = new CoursePackageTecordVo();
                                BeanUtils.copyProperties(coursePackage, coursePackageTecordVo);
                                coursePackageTecordVo.setOrderId(item.getOrderId());
                                List<StudentCoursePackage> studentlist = studentCoursePackageMapper.selectByOrderId(item.getOrderId());
                                //学习人数
                                coursePackageTecordVo.setStudyCount(studentlist.size());
                                //课程数量
                                int courseCount = 0;
                                //课程包视频总时长
                                int videoDuration = 0;
                                //该课程包随堂考人数
                                int quizCount = 0;
                                //该课程包随堂考人数合格人数
                                int quizPassCount = 0;

                                List<Course> courseList = coursePackageService.findCourse(coursePackage);
                                for (Course course : courseList) {
                                    if (course.getFiles() != null && course.getFiles().size() > 0) {
                                        for (CourseFile courseFile : course.getFiles()) {
                                            videoDuration += courseFile.getSeconds();
                                        }
                                    }
                                }
                                for (StudentCoursePackage studentCoursePackage : studentlist) {
                                    boolean mark = true;
                                    //调用保利威接口判断学员该课程包是否全部学完
                                    //查找课程包包含的视频集合
                                    for (Course course : courseList) {
                                        if (course.getFiles() != null && course.getFiles().size() > 0) {
                                            for (CourseFile courseFile : course.getFiles()) {
                                                ViewLog viewLog = new ViewLog();
                                                viewLog.setSessionId(studentCoursePackage.getStudentId().toString());
                                                viewLog.setVideoId(courseFile.getPath());
                                                List<ViewLog> viewLogList = viewLogMapper.queryAll(viewLog);
                                                if (viewLogList != null && viewLogList.size() > 0) {
                                                    if (viewLogList.get(0).getPlayDuration() + 10 < Integer.valueOf(viewLogList.get(0).getDuration())
                                                            || Integer.valueOf(viewLogList.get(0).getCurrentTimes() + 10) < Integer.valueOf(viewLogList.get(0).getDuration())) {
                                                        mark = false;
                                                        break;

                                                    }
                                                } else {
                                                    mark = false;
                                                    break;
                                                }
                                            }
                                        }
                                        if (mark == false) {
                                            break;
                                        }
                                    }
                                    if (mark == true) {
                                        quizCount++;
                                    }
                                    List<QuizRecord> quizRecordList = quizRecordMapper.PassQuiz(studentCoursePackage.getStudentId(), coursePackage.getId());
                                    //该课程包下的随堂考已经通过
                                    if (quizRecordList != null && quizRecordList.size() > 0) {
                                        //存在有效随堂考记录
                                        for (QuizRecord quizRecord : quizRecordList) {
                                            if (whetherOverdue(quizRecord.getOrderId())) {
                                                quizPassCount++;
                                                break;
                                            }
                                        }
                                    }

                                }

                                coursePackageTecordVo.setCourseCount(courseCount);
                                coursePackageTecordVo.setQuizCount(quizCount);
                                coursePackageTecordVo.setVideoDuration(videoDuration);
                                coursePackageTecordVo.setCourseCount(courseList.size());
                                coursePackageTecordVo.setQuizPassCount(quizPassCount);
                                result.add(coursePackageTecordVo);
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    @Override
    public List<StudentStudyTimeTecordVo> selectByOrderId(Integer orderId) {
        List<StudentStudyTimeTecordVo> result = new ArrayList<>();
        List<StudentCoursePackage> studentlist = studentCoursePackageMapper.selectByOrderId(orderId);
        if (studentlist != null && studentlist.size() > 0) {
            for (StudentCoursePackage studentCoursePackage : studentlist) {
                Student student = studentMapper.selectByPrimaryKey(studentCoursePackage.getStudentId());

                StudentStudyTimeTecordVo studentStudyTimeTecordVo = new StudentStudyTimeTecordVo();
                studentStudyTimeTecordVo.setStudentId(student.getId());
                studentStudyTimeTecordVo.setName(student.getName());
                studentStudyTimeTecordVo.setTel(student.getTel());
                //已学视频数量
                int learnCount = 0;
                // 已学习时长
                int playDuration = 0;
                //剩余学习时长
                int surplusDuration = 0;

                //课程包视频总时长
                int videoDuration = 0;

                CoursePackage coursePackage = coursePackageMapper.selectByPrimaryKey(studentCoursePackage.getPackageId());
                List<Course> courseList = coursePackageService.findCourse(coursePackage);
                for (Course course : courseList) {
                    if (course.getFiles() != null && course.getFiles().size() > 0) {
                        for (CourseFile courseFile : course.getFiles()) {
                            videoDuration += courseFile.getSeconds();
                            ViewLog viewLog = new ViewLog();
                            viewLog.setSessionId(studentCoursePackage.getStudentId().toString());
                            viewLog.setVideoId(courseFile.getPath());
                            List<ViewLog> viewLogList = viewLogMapper.queryAll(viewLog);
                            //判断视频是否学完，记录已学习时长
                            if (viewLogList != null && viewLogList.size() > 0) {
                                if (viewLogList.get(0).getPlayDuration() + 10 >= Integer.valueOf(viewLogList.get(0).getDuration())
                                        && Integer.valueOf(viewLogList.get(0).getCurrentTimes() + 10) >= Integer.valueOf(viewLogList.get(0).getDuration())) {
                                    learnCount++;
                                }
                                playDuration += viewLogList.get(0).getPlayDuration();
                            }
                        }
                    }
                }

                surplusDuration = videoDuration - playDuration;
                if (surplusDuration < 0) {
                    surplusDuration = 0;
                    playDuration = videoDuration;
                }
                studentStudyTimeTecordVo.setLearnCount(learnCount);
                studentStudyTimeTecordVo.setPlayDuration(playDuration);
                studentStudyTimeTecordVo.setSurplusDuration(surplusDuration);
                result.add(studentStudyTimeTecordVo);
            }
        }

        return result;
    }

    @Override
    public List<StudentQuizRecordVo> selectQuizRecordByOrderId(Integer orderId) {
        List<StudentQuizRecordVo> result = new ArrayList<>();

        List<StudentCoursePackage> studentlist = studentCoursePackageMapper.selectByOrderId(orderId);

        if (studentlist != null && studentlist.size() > 0) {

            CoursePackage coursePackage = coursePackageMapper.selectByPrimaryKey(studentlist.get(0).getPackageId());
            List<Course> courseList = coursePackageService.findCourse(coursePackage);

            for (StudentCoursePackage studentCoursePackage : studentlist) {
                boolean mark = true;
                //调用保利威接口判断学员该课程包是否全部学完
                //查找课程包包含的视频集合
                for (Course course : courseList) {
                    if (course.getFiles() != null && course.getFiles().size() > 0) {
                        for (CourseFile courseFile : course.getFiles()) {
                            ViewLog viewLog = new ViewLog();
                            viewLog.setSessionId(studentCoursePackage.getStudentId().toString());
                            viewLog.setVideoId(courseFile.getPath());
                            List<ViewLog> viewLogList = viewLogMapper.queryAll(viewLog);
                            if (viewLogList != null && viewLogList.size() > 0) {
                                if (viewLogList.get(0).getPlayDuration() + 10 < Integer.valueOf(viewLogList.get(0).getDuration())
                                        || Integer.valueOf(viewLogList.get(0).getCurrentTimes() + 10) < Integer.valueOf(viewLogList.get(0).getDuration())) {
                                    mark = false;
                                    break;

                                }
                            } else {
                                mark = false;
                                break;
                            }
                        }
                    }
                    if (mark == false) {
                        break;
                    }
                }
                //课程包视频全部看完才能看完，统计可以参加随堂考的学生集合
                if (mark == true) {
                    StudentQuizRecordVo studentQuizRecordVo = new StudentQuizRecordVo();
                    studentQuizRecordVo.setOrderId(orderId);
                    studentQuizRecordVo.setStudentId(studentCoursePackage.getStudentId());
                    Student student = studentMapper.selectByPrimaryKey(studentCoursePackage.getStudentId());
                    studentQuizRecordVo.setTel(student.getTel());
                    studentQuizRecordVo.setName(student.getName());

                    QuizRecord quizRecord = new QuizRecord();
                    quizRecord.setOrderId(orderId);
                    List<QuizRecord> quizRecordList = quizRecordMapper.queryAll(quizRecord);

                    if (quizRecordList != null && quizRecordList.size() > 0) {
                        studentQuizRecordVo.setQuizTimes(quizRecordList.size());
                        studentQuizRecordVo.setClassHours(quizRecordList.get(0).getClassHours());
                        studentQuizRecordVo.setGrade(quizRecordList.get(0).getGrade());
                    } else {
                        studentQuizRecordVo.setClassHours(0);
                        studentQuizRecordVo.setQuizTimes(0);
                        studentQuizRecordVo.setGrade(0d);
                    }

                    result.add(studentQuizRecordVo);
                }
            }
        }
        return result;
    }

    /**
     * 获取精确到秒的时间戳
     *
     * @return
     */
    public static int getSecondTimestamp(Date date) {
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0, length - 3));
        } else {
            return 0;
        }
    }


}
